import { Manager } from "@/models/Manager";
import { Store } from "@/models/Store";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { z } from "zod";

const storeRoute = new Hono();

storeRoute.get("/list", async (c) => {
  let [list, count] = await Store.findAndCount();
  return c.json({ message: "success", code: 200, data: { list, count } });
});

storeRoute.get("/detail", async (c) => {
  let payload = c.get("jwtPayload");

  let id = payload.id;
  let manager = await Manager.findOne({
    where: { id },
    relations: {
      store: true,
    },
  });
  return c.json({
    message: "success",
    code: 200,
    data: { store: manager.store },
  });
});

const addSchema = z.object({
  name: z.string(),
  image: z.string(),
  phone: z.string(),
  address: z.string(),
});

const updateSchema = z.object({
  id: z.coerce.number(),
  name: z.string(),
  image: z.string(),
  phone: z.string(),
  address: z.string(),
});

storeRoute.post("/add", async (c) => {
  let body = await c.req.parseBody();
  let result = addSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let store = new Store();
  store.name = result.data.name;
  store.image = result.data.image;
  store.phone = result.data.phone;
  store.address = result.data.address;

  await store.save();

  return c.json({ message: "hello", code: 200, data: store });
});

storeRoute.post("/edit", async (c) => {
  let body = await c.req.parseBody();
  let result = updateSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let store = await Store.findOneBy({ id: result.data.id });

  if (!store) {
    throw new HTTPException(404, { message: "门店不存在" });
  }

  store.name = result.data.name;
  store.image = result.data.image;
  store.phone = result.data.phone;
  store.address = result.data.address;

  await store.save();

  return c.json({ message: "hello", code: 200, data: store });
});

export default storeRoute;
